<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2023-10-27 13:58:55
 * @LastEditors: swc shanwenchao12138@163.com
 * @LastEditTime: 2025-03-07 08:55:30
-->

<template>
  <div class="init-container">
    <vxe-modal
      v-if="!isOpenFun"
      v-bind="cf.compBind"
      :zIndex="202 + $srv.getStore().state.App.modalCount"
      @show="onShow"
      @hide="onHide"
      @confirm="onConfirm"
      @cancel="onCancel"
      @close="onClose"
      @zoom="onZoom"
    >
      <template #default v-if="isFunPanel">
        <div class="default-content">
          <div
            class="group-content"
            v-for="(k, idx) of Object.keys(cf.compConf.group)"
            :key="idx"
          >
            <h3 class="title">{{ $srv.getI18nBySrv(k) }}</h3>
            <div v-if="$srv.getx(cf.compConf, 'group.' + k, false)">
              <div v-for="(item, index) of cf.compConf.group[k]" :key="index">
                <o-base-form
                  v-if="item['form']"
                  :ref="item.form.uiID"
                  :mode="1"
                  @on-change="onAttrChange(item.form.uiID, $event)"
                />
                <o-simple-table
                  v-if="item['table']"
                  :ref="item.table.uiID"
                  :columns="item.table.columns"
                  :allowEdit="true"
                  :disabled="false"
                />
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #default v-else-if="isUnitePanel">
        <div class="default-content">
          <unite-panel
            :compBoxInfo="compBoxInfo"
            @on-update="onUnitePanelUpdate"
            ref="unitePanel"
            :config="unitePanelConfig"
          />
        </div>
      </template>
    </vxe-modal>
    <o-magic-box :id="modID" v-if="isOpenFun" :config="magicBoxCf" />
  </div>
</template>

<script lang="ts">
import { N_oMagicbox } from '../o-magicbox/types';
import { I_cmd, T_cmd, T_srv, Tsrv, ifs, ts, unitePanel, vue } from './config';
import { N_oInteraction } from './types';

@T_srv.comp({
  name: 'oInteraction',
  components: { unitePanel }
})
export default class oInteraction extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  // 打开组件的名称
  @T_srv.prop({
    required: false,
    type: String,
    default: ''
  })
  openCompName: string;

  // modalID
  @T_srv.prop({
    required: true,
    type: Number,
    default: -1
  })
  id: number;

  @T_srv.prop({
    required: false,
    type: String,
    default: ''
  })
  cmd: N_oInteraction.V_cmd;

  @T_srv.prop({
    required: false,
    type: String,
    default: ''
  })
  workID: string;

  @T_srv.prop({
    required: false,
    type: Object,
    default: () => {}
  })
  compBind: Object;

  @T_srv.prop({
    required: false,
    type: Object,
    default: () => {}
  })
  compConf: object;

  // 事件名
  @T_srv.prop({
    required: false,
    type: Array,
    default: () => []
  })
  eventNames: Array<string>;

  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  config: N_oInteraction.I_conf;

  // @T_srv.ref('attrForm') refAttrForm: any;

  @T_srv.watch('config')
  onChg(val) {
    this.init();
  }

  /* 组件名 */
  private name: string = 'oInteraction';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  public isFunPanel: boolean = false;

  public isUnitePanel: boolean = false;

  public isOpenFun: boolean = false;

  public isDialog: boolean = false;

  public cf: N_oInteraction.I_conf = {
    // 打开组件的名称
    openCompName: '',
    workID: '',
    cmd: null,
    // 组件绑定
    compBind: {},
    // 组件配置，用在funPanel  openFun dialog为{}
    compConf: {}
    // 事件名
    // eventNames: []
  };

  public magicBoxCf: N_oMagicbox.I_cf = {};

  // public modID: number = parseInt(Tsrv.utils.custUUID(8, 10, 'number'), 10);
  public modID: number;

  private listenBusEventName: string = Tsrv.utils.custUUID(8, 16);

  private selectColumns: Array<any> = [];

  private unitePanelConfig: any = null;

  private unitePanelsData: any = null;

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  init() {
    if (Tsrv.utils.noValue(this.openCompName)) {
      this.cf.openCompName = this.config?.openCompName ?? '';
    }
    this.cf.compBind = this.compBind ?? this.config?.compBind ?? {};
    this.cf.compConf = this.compConf ?? this.config?.compConf ?? {};
    // this.cf.eventNames = this.eventNames ?? this.config?.eventNames ?? [];
    if (Tsrv.utils.noValue(this.cmd)) {
      this.cf.cmd = this.config?.cmd ?? N_oInteraction.V_cmd.DIALOG;
    }
    if (Tsrv.utils.noValue(this.workID)) {
      this.cf.workID = this.config?.workID ?? '';
    }

    if (this.cf.cmd === N_oInteraction.V_cmd.DIALOG) {
      this.isDialog = true;
      this.isFunPanel = false;
      this.isOpenFun = false;
      this.isUnitePanel = false;
    } else if (this.cf.cmd === N_oInteraction.V_cmd.FUN_PANEL) {
      this.isDialog = false;
      this.isFunPanel = true;
      this.isOpenFun = false;
      this.isUnitePanel = false;
    } else if (this.cf.cmd === N_oInteraction.V_cmd.UNITE_PANEL) {
      this.isDialog = false;
      this.isFunPanel = false;
      this.isOpenFun = false;
      this.isUnitePanel = true;
      this.unitePanelConfig = {
        panels: this.cf.compConf.panels,
        layoutStyle: this.cf.compConf.layoutStyle,
        workID: this.cf.workID,
        style: {
          height:
            this.cf.compConf?.style?.height ||
            this.cf.compConf?.style?.minHeight ||
            'auto',
          width:
            this.cf.compConf?.style?.width ||
            this.cf.compConf?.style?.minWidth ||
            'auto'
        }
      };
    } else if (this.cf.cmd === N_oInteraction.V_cmd.OPEN_FUN) {
      this.isDialog = false;
      this.isFunPanel = false;
      this.isOpenFun = true;
      this.isUnitePanel = false;
      if (
        Tsrv.getx(
          this.cf.compConf.magicboxCf,
          'source.filter.initSearch',
          false
        )
      ) {
        if (
          JSON.stringify(
            this.cf.compConf.magicboxCf.source.filter.initSearch
          ).indexOf('$') > -1
        ) {
          const f = new ts.T_filter();
          f.filter = this.cf.compConf.magicboxCf.source.filter.initSearch;
          this.cf.compConf.magicboxCf.source.filter.initSearch = f;
        }
      }
      this.magicBoxCf = this.cf.compConf.magicboxCf;
    }
    // 系统自定义的createmodal弹窗层级需要参与到modalCount中
    if (this.isOpenFun) {
      this.$store.dispatch('addModalCount');
      this.modID = Tsrv.getStore().state.App.modalCount;
    }
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.$nextTick(() => {
      if (this.isFunPanel) {
        this.initFunPanel();
      }
    });
    if (this.isOpenFun && !Tsrv.utils.noValue(this.modID)) {
      this.$bus.$on(`modal_${this.modID}`, e => {
        this.openfunCallback(e);
      });
    }
  }

  // openfun 返回回调
  private openfunCallback(res: any) {
    if (Tsrv.utils.noValue(res)) {
      this.onCancel(null);
    } else {
      if (!Tsrv.utils.noValue(res?._trigger_)) {
        this.selectColumns = res?.data;
        this.onCustomBtnClick(res._trigger_);
      } else {
        this.selectColumns = res;
        this.onConfirm(null);
      }
    }
  }

  initFunPanel() {
    const group: N_oInteraction.I_group = this.cf.compConf.group;
    Object.keys(group).forEach(k => {
      for (const o of group[k]) {
        if (o?.form) {
          const ref: any = this.$refs[o.form.uiID];
          const columns: Array<any> = ref[0].transformColumns(o.form.fields);
          // const columns: Array<any> = ref[0].transformColumns(this.handleM2oFieldI18n(o.form.fields));
          // 初始化栏位
          ref[0].setColumns(columns);
          // 初始化值
          const formInitVal = this?.cf?.compConf?.initValue?.formData[
            o.form.uiID
          ];
          if (!Tsrv.noValue(formInitVal)) {
            ref[0].setFormData(this.fvArrToObj(formInitVal));
          }
          if (o?.form?.formColumnNum) {
            ref[0].setColumnNumber(o.form.formColumnNum, true);
          }
        }
        if (o?.table) {
          const ref: any = this.$refs[o.table.uiID];
          const tableInitVal = this?.cf?.compConf?.initValue?.tableData[
            o.table.uiID
          ];
          if (!Tsrv.noValue(tableInitVal)) {
            ref[0].setData(this.fvArrToRows(tableInitVal));
          }
        }
      }
    });
  }

  private fvArrToObj(arr: Array<ifs.I_fv>): any {
    const obj: any = {};
    arr.forEach((o: any) => {
      obj[o.field] = o.value;
    });
    return obj;
  }

  private fvArrToRows(arr: Array<Array<ifs.I_fv>>): any {
    const rows: Array<any> = [];
    arr.forEach((o: Array<ifs.I_fv>, i: number) => {
      const rObj: any = {};
      o.forEach((r: ifs.I_fv) => {
        rObj[r.field] = r.value;
      });
      rows.push(rObj);
    });
    return rows;
  }

  private handleM2oFieldI18n(
    fields: Array<N_oInteraction.I_field>
  ): Array<N_oInteraction.I_field> {
    fields.forEach((o: N_oInteraction.I_field) => {
      if (o.many2one.toTable && o.many2one.toField) {
        Tsrv.getFunConf(o.many2one.toTable).then(res => {
          if (res.isErr()) {
            console.error(res.errmsg);
          } else {
            const cf = res.getReturnData(o.many2one.toTable);
            if (Tsrv.noValue(cf?.funI18nFields)) {
              // o.many2one.toField, o.field
              cf?.funI18nFields.includes(o.many2one.toField) &&
                (o['isI18n'] = true);
            }
          }
        });
      }
    });
    return fields;
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
    if (this.isOpenFun && !Tsrv.utils.noValue(this.modID)) {
      this.$bus.$off(`modal_${this.modID}`);
    }
  }

  onShow(e) {
    this.$emit('on-event', {
      name: 'on-show',
      res: this.getRes('show'),
      e
    });
  }

  onHide(e) {
    this.$emit('on-event', {
      name: 'on-hide',
      res: this.getRes('hide'),
      e
    });
  }

  onConfirm(e) {
    const res = this.getRes('confirm');
    this.$emit('on-event', {
      name: 'on-confirm',
      res,
      e
    });
    this.$bus.$emit(`modal_${this.id}`, res);
  }

  onCustomBtnClick(e) {
    const res = this.getRes('customBtn', e);
    this.$emit('on-event', {
      name: 'on-customBtn',
      res,
      e
    });
    this.$bus.$emit(`modal_${this.id}`, res);
  }

  onCancel(e) {
    const res = this.getRes('cancel');
    this.$emit('on-event', {
      name: 'on-cancel',
      res,
      e
    });
    this.$bus.$emit(`modal_${this.id}`, res);
  }

  onClose(e) {
    this.$emit('on-event', {
      name: 'on-close',
      res: this.getRes('close'),
      e
    });
  }

  getRes(
    p: 'show' | 'hide' | 'confirm' | 'cancel' | 'close' | 'zoom' | 'customBtn',
    params: any = null
  ): any {
    switch (p) {
      case 'confirm':
        return this.confirmHandle();
      // break;
      case 'customBtn':
        return this.customBtnHandle(params);
      // break;
      case 'cancel':
        return this.cancelHandle();
      //  break;
      case 'close':
        return this.closeHandle();
      // break;
      case 'show':
        return this.showHandle();
      // break;
      case 'hide':
        return this.hideHandle();
      // break;
      case 'zoom':
        return this.zoomHandle();
      // break;
      default:
        this.$msg(`-551,FE,90,unknown error`);
    }
    return null;
  }

  confirmHandle(): any {
    let d: any = {};
    if (this.isFunPanel) {
      d = this.getData();
    } else if (this.isOpenFun) {
      d = { selectColumns: this.selectColumns };
    }
    if (this.isUnitePanel) {
      d = this.getUnitePanelData();
    }
    return {
      workID: this.cf.workID,
      action: 'confirm',
      data: d
    };
  }

  customBtnHandle(p: any): any {
    let d: any = {};
    if (this.isOpenFun) {
      d = {
        action: p?.data?.key,
        spName: p?.data?.action || '',
        selectColumns: this.selectColumns
      };
    }
    return {
      workID: this.cf.workID,
      action: 'customBtn',
      data: d
    };
  }

  cancelHandle(): any {
    let d: any = {};
    if (this.isFunPanel) {
      d = this.getData();
    }
    if (this.isUnitePanel) {
      d = this.getUnitePanelData();
    }
    return {
      workID: this.cf.workID,
      action: 'cancel',
      data: d
    };
  }

  closeHandle(): any {
    let d: any = {};
    if (this.isFunPanel) {
      d = this.getData();
    }
    if (this.isUnitePanel) {
      d = this.getUnitePanelData();
    }
    return {
      workID: this.cf.workID,
      action: 'close',
      data: d
    };
  }

  showHandle(): any {
    let d: any = {};
    if (this.isFunPanel) {
      d = this.getData();
    }
    if (this.isUnitePanel) {
      d = this.getUnitePanelData();
    }
    return {
      workID: this.cf.workID,
      action: 'show',
      data: d
    };
  }

  hideHandle(): any {
    let d: any = {};
    if (this.isFunPanel) {
      d = this.getData();
    }
    if (this.isUnitePanel) {
      d = this.getUnitePanelData();
    }
    return {
      workID: this.cf.workID,
      action: 'hide',
      data: d
    };
  }

  zoomHandle(): any {
    let d: any = {};
    if (this.isFunPanel) {
      d = this.getData();
    }
    if (this.isUnitePanel) {
      d = this.getUnitePanelData();
    }
    return {
      workID: this.cf.workID,
      action: 'zoom',
      data: d
    };
  }

  onZoom(e) {
    this.$emit('on-event', {
      name: 'on-zoom',
      res: this.getRes('zoom'),
      e
    });
  }

  onAttrChange(uiID: string, e: any) {
    this.$emit('on-event', { name: 'on-attr-change', uiID, e });
  }

  getTableData(uiID: string): object {
    const rd: Array<any> = [];
    const d: Array<any> = Tsrv.getx(
      this.cf,
      `compConf.initValuetableData.${uiID}`,
      []
    );
    if (!Tsrv.utils.noValue(d)) {
      d.forEach(el => {
        rd.push({ [el.field]: el.value });
      });
    }
    return rd;
  }

  getData(): object {
    const d: object = {};
    Object.keys(this.cf.compConf.group).forEach(k => {
      this.cf.compConf.group[k].forEach(el => {
        if (el?.form && el?.form.uiID !== '') {
          const ref: any = this.$refs[el.form.uiID];
          d[el.form.uiID] = ref[0].getData();
        }
        if (el?.table && el?.table.uiID !== '') {
          const ref: any = this.$refs[el.table.uiID];
          const _tD = ref[0].getData();
          const tD: Array<ifs.I_fv> = [];
          _tD.forEach(ele => {
            Object.keys(ele).forEach(key => {
              if (key !== '_index' && key !== '_rowKey') {
                tD.push({ field: key, value: ele[key] } as ifs.I_fv);
              }
            });
          });
          d[el.table.uiID] = tD;
        }
      });
    });
    return d;
  }

  private getUnitePanelData(): any {
    const ref: any = this.$refs['unitePanel'];
    ref.getData();
    return this.unitePanelsData;
  }

  private onUnitePanelUpdate(e: any) {
    this.unitePanelsData = e;
  }
}
</script>
<style lang="scss" scoped>
.default-content {
  border: 1px solid #ccc;
  margin-bottom: 6px;
  height: calc(100% - 6px);
  .group-content {
    height: 100%;
    .title {
      margin: 6px 6px 6px 10px;
    }
  }
  .title {
    margin: 6px 6px 6px 10px;
  }
}
</style>
